package cn.com.scitc.user;

import cn.com.scitc.dao.ManagerDao;
import cn.com.scitc.model.Manager;
import cn.com.scitc.server.MyMd5;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "UserUpdataServlet",urlPatterns = "/manager/user/update")
public class UserUpdateServlet extends HttpServlet {
    private Manager manager;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            String id = request.getParameter("id");
            ManagerDao managerDao = new ManagerDao();
            manager = managerDao.findById(Integer.parseInt(id));
            if(validation(request)){
                request.getSession().setAttribute("msg","更新成功！！");
                managerDao.updateByPrimaryKey(manager);
                response.sendRedirect("list");

            }else {
                request.getSession().setAttribute("msg","服务端更新失败！！");
                response.sendRedirect("edit?id=" + id);
                return;
            }


        }catch (Exception e){
            e.printStackTrace();
            request.getSession().setAttribute("msg","更新失败！！");
            response.sendRedirect("list");
            return;
        }

    }


    private boolean validation(HttpServletRequest request){
        String loginId = request.getParameter("loginId");
        if(loginId == null || loginId.length() < 8 || loginId.length() > 8){
            System.out.println("账号不通过！！");
            return false;
        }
        manager.setLoginid(loginId);

        String realName = request.getParameter("realName");
        if(realName == null || realName.length() < 2 || realName.length() > 5){
            System.out.println("姓名不通过！！" + realName);
            return false;
        }
        manager.setRealname(realName);

        String pwd = request.getParameter("pwd");
        if(pwd == null || pwd.length() < 6 || pwd.length() > 20){
            System.out.println("密码不通过！！");
            return false;
        }
        manager.setPwd(MyMd5.signPwd(pwd));

        return true;
    }

}
